package com.hippy.erya.config.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hippy.erya.config.jsonobj.ResponseJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestControllerAdvice
public class LogResponseAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }


    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (!(o instanceof ResponseJson)) {
            return o;
        }
        ResponseJson responseJson = (ResponseJson) o;
        try {
            o = responseBodyProcess(responseJson);
        } catch (Exception e) {

        }
        return o;
    }

    private Map<String, String> responseBodyProcess(ResponseJson responseJson) throws IOException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException {
        Map<String, String> map = new HashMap<>(16);
        // 格式化请求报文
        String jsonString = JSONObject.toJSONString(responseJson,
                // 格式化json报文，返回给终端的最好不要格式化，可以降低报文大小
                SerializerFeature.PrettyFormat,
                SerializerFeature.QuoteFieldNames,
                // 是否输出值为null的字段，默认为false，即不设置即为false
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.DisableCircularReferenceDetect
        );
        log.info("返回报文={}", jsonString);
        //直接返回
        map=JSONObject.parseObject(jsonString,Map.class);
        return map;
    }

}
